package com.sicnu.cheer.profileset.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sicnu.cheer.generalmodule.util.DateUtil;
import com.sicnu.cheer.generalmodule.util.SharedPreferencesUtil;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.generalmodule.wheelview.OnWheelChangedListener;
import com.sicnu.cheer.generalmodule.wheelview.WheelView;
import com.sicnu.cheer.generalmodule.wheelview.adapters.ArrayWheelAdapter;
import com.sicnu.cheer.profileset.R;
import com.sicnu.cheer.profileset.config.Constant;
import com.sicnu.cheer.profileset.datepicker.DatePicker;
import com.sicnu.cheer.profileset.model.CityModel;
import com.sicnu.cheer.profileset.model.DistrictModel;
import com.sicnu.cheer.profileset.model.ProvinceModel;
import com.sicnu.cheer.profileset.service.XmlParserHandler;

import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import cn.aigestudio.datepicker.cons.DPMode;

/**
 * Created by cheer on 2017/2/16.
 */

public class DialogsUtil implements OnWheelChangedListener {

    public static void showChangePasswordDialog(final Activity activity,final InputDialogCallback callback) {
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_change_password, null);
        final EditText oldET = (EditText) view.findViewById(R.id.old_password);
        final EditText newET = (EditText) view.findViewById(R.id.new_password);

        TextView textView = (TextView) view.findViewById(R.id.title);
        textView.setText("修改密码");

        final Dialog dialog = new Dialog(activity);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable());
        window.requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindow().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        window.getAttributes().width = displayMetrics.widthPixels / 5 * 4;
        dialog.show();
        Button submit = (Button) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String oldValue = oldET.getText().toString().trim();
                String newValue=newET.getText().toString().trim();
                if (StringUtils.isEmpty(oldValue)) {
                    UIHelper.ToastMessage(activity, "旧密码不能为空");
                } else if (StringUtils.isEmpty(newValue)){

                    UIHelper.ToastMessage(activity, "新密码不能为空");
                }else{
                    if (callback != null) {
                        callback.confirmCallBack(oldValue, newValue);
                    }
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.cancelCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }
    /**
     * 带输入框对话框点击按钮回调接口
     */
    public interface InputDialogCallback {
        /**
         * 确定按钮回调方法
         *
         * @param oldValue  老密码
         * @param newValue 新密码
         */
        void confirmCallBack(String oldValue, String newValue);

        /**
         * 取消按钮的回调方法
         */
        void cancelCallBack();

    }


    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;

    public void showHometownChooseDialog(final Context context, final DialogCallback callback) {
        showHometownChooseDialog(context, "取消", "确定",callback);
    }

    /**
     * 选择家乡对话框
     *
     * @param context
     * @param submitButton
     * @param cancelButton
     * @param callback
     */
    public void showHometownChooseDialog(final Context context, String submitButton, String cancelButton, final DialogCallback callback) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_hometown_choose, null);
        ((TextView) view.findViewById(R.id.title)).setText("选择家乡");


        mViewProvince = (WheelView) view.findViewById(R.id.id_province);
        mViewCity = (WheelView) view.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
        //addListener
        mViewProvince.addChangingListener(this);
        mViewCity.addChangingListener(this);
        mViewDistrict.addChangingListener(this);
        //setUpData
        initProvinceDatas(context);
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<>(context, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities(context);
        updateAreas(context);

        //将滚动视图添加到对话框中显示
        final Dialog dialog = new Dialog(context);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new BitmapDrawable());
        window.requestFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(view);
        dialog.setCancelable(true);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        window.getAttributes().width = wm.getDefaultDisplay().getWidth() / 5 * 4;
        dialog.show();

        Button submit = (Button) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //保存家乡到本地
                SharedPreferencesUtil.saveUserItem(context, Constant.HOMETOWN,
                        mCurrentProviceName + "-" + mCurrentCityName + "-" + mCurrentDistrictName);
                if (callback != null) {
                    callback.confirmCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.cancelCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            updateCities(wheel.getContext());
        } else if (wheel == mViewCity) {
            updateAreas(wheel.getContext());
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     *
     * @param context
     */
    private void updateAreas(Context context) {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(context, areas));
        mViewDistrict.setCurrentItem(0);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     *
     * @param context
     */
    private void updateCities(Context context) {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(context, cities));
        mViewCity.setCurrentItem(0);
        updateAreas(context);
    }

    /**
     * 默认取消确定按钮
     *
     * @param context
     * @param defaultDate
     * @param callback
     */
    public static void showBirthdayChooseDialog(final Context context, String defaultDate, final DialogCallback callback) {
        showBirthdayChooseDialog(context, "取消", "确定", defaultDate, callback);
    }

    /**
     * 选择生日的对话框
     *
     * @param context
     * @param submitButton
     * @param cancelButton
     * @param defaultDate
     * @param callback
     */
    public static void showBirthdayChooseDialog(final Context context, String submitButton, String cancelButton, String defaultDate, final DialogCallback callback) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_birthday_choose, null);
        ((TextView) view.findViewById(R.id.title)).setText("选择生日");

        Calendar c = Calendar.getInstance();
        Date date=null;
        if (StringUtils.isEmpty(defaultDate)){
            date=new Date();
        }else {
            date = DateUtil.convertDate(defaultDate, "yyyy-MM-dd");
        }
        c.setTime(date);
        DatePicker picker = (DatePicker) view.findViewById(R.id.birthday_dp);
        //设置默认日期为当前用户的生日
        if (StringUtils.isEmpty(defaultDate)){
            picker.setDate(c.get(Calendar.YEAR)-20, c.get(Calendar.MONTH) + 1);
        }else {
            picker.setDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1);
        }
        picker.setFestivalDisplay(false);
        picker.setTodayDisplay(true);
        picker.setHolidayDisplay(false);
        picker.setDeferredDisplay(false);
        picker.setMode(DPMode.SINGLE);
        picker.setOnDatePickedListener(new DatePicker.OnDatePickedListener() {
            @Override
            public void onDatePicked(String date) {
                final String birthday = DateUtil.formateDate(DateUtil.convertDate(date, Constant.yyyy_MM_dd_PATTERN), Constant.yyyy_MM_dd_PATTERN);
                SharedPreferencesUtil.saveUserItem(context, "birthday", birthday);
            }
        });

        addViewToDialog(context, view, callback);
    }

    /**
     * 默认确定取消按钮
     *
     * @param context
     * @param defaultSex
     * @param callback
     */
    public static void showSexChooseDialog(final Context context, int defaultSex, final DialogCallback callback) {
        showSexChooseDialog(context, "取消", "确定", defaultSex, callback);
    }

    /**
     * 自定义dialog设置性别
     *
     * @param context
     * @param submitButton 提交
     * @param callback
     * @param defaultSex   默认性别
     */
    public static void showSexChooseDialog(final Context context, String submitButton, String cancelButton, int defaultSex, final DialogCallback callback) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_sex_choose, null);
        ((TextView) view.findViewById(R.id.title)).setText("选择性别");
        final ImageView girl = (ImageView) view.findViewById(R.id.girl_iv);
        final ImageView boy = (ImageView) view.findViewById(R.id.boy_iv);
        if (defaultSex == 1) {
            boy.setSelected(true);
        } else {
            girl.setSelected(true);
        }
        girl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                girl.setSelected(true);
                boy.setSelected(false);
                SharedPreferencesUtil.saveUserItem(context, "sex", "女");
            }
        });
        boy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boy.setSelected(true);
                girl.setSelected(false);
                SharedPreferencesUtil.saveUserItem(context, "sex", "男");
            }
        });

        addViewToDialog( context, view, callback);
    }

    /**
     * 将自定义view加到对话框中进行显示
     *
     * @param context
     * @param view
     * @param callback
     */
    private static void addViewToDialog( final Context context, View view, final DialogCallback callback) {
        final Dialog dialog = new Dialog(context);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new BitmapDrawable());
        window.requestFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(view);
        dialog.setCancelable(true);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        window.getAttributes().width = wm.getDefaultDisplay().getWidth() / 5 * 4;
        dialog.show();

        Button submit = (Button) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.confirmCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.cancelCallBack();
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }

    /**
     * 对话框点击按钮回调接口
     */
    public interface DialogCallback {
        /**
         * 确定按钮回调方法
         */
        void confirmCallBack();

        /**
         * 取消按钮的回调方法
         */
        void cancelCallBack();

    }

    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    protected static String mCurrentZipCode = "";

    /**
     * 解析省市区的XML数据
     */

    protected void initProvinceDatas(Context context) {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = context.getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }
}
